/*
 * Copyright 2010-2011 CGT&DC ISA RAS
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package websolve.workflow.runtime;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;

public abstract class Task implements Runnable {

    private String name;
    protected Map<String, Parameter> inParams = new HashMap<String, Parameter>();
    protected Map<String, Parameter> outParams = new HashMap<String, Parameter>();
    private String state = TaskState.WAITING;
    private String info;
    private String error;
    private String startTime;
    private String finishTime;
    private SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss SSS");

    public Task(String name) {
        this.name = name;
    }

    public Task setInput(String name, Parameter param) {
        Parameter myParam = inParams.get(name);
        if (param != null && myParam != null && myParam.isCompatibleWith(param)) {
            param.setConnected(true);
            param.incrementConsumerCount();
            myParam.decrementConsumerCount();
            inParams.put(name, param);
            return this;
        } else {
            throw new IllegalArgumentException();
        }
    }

    public Task setInputValue(String name, Object value) {
        Parameter myParam = inParams.get(name);
        if (myParam != null) {
            myParam.setValue(value);
            return this;
        } else {
            throw new IllegalArgumentException();
        }
    }

    public Parameter getOutput(String name) {
        return outParams.get(name);
    }

    public Object getOutputValue(String name) {
        if (outParams.containsKey(name)) {
            return outParams.get(name).getValue();
        } else {
            return null;
        }
    }

    public Map<String, Object> getOutputValues() {
        Map<String, Object> values = new HashMap<String, Object>();
        for (Entry<String, Parameter> paramE : getOutputs().entrySet()) {
            values.put(paramE.getKey(), paramE.getValue().getValue());
        }
        return values;
    }

    public Map<String, Parameter> getInputs() {
        return Collections.unmodifiableMap(inParams);
    }

    public Map<String, Parameter> getOutputs() {
        return Collections.unmodifiableMap(outParams);
    }

    public String getName() {
        return name;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        boolean stateChanged = !this.state.equals(state);
        this.state = state;
        log.fine("Task " + name + ": " + state);

        if (stateChanged) {

            // start time
            if (state.equals(TaskState.RUNNING)) {
                startTime = sdf.format(new Date(System.currentTimeMillis()));
            }

            // finish time
            if (state.equals(TaskState.DONE) || state.equals(TaskState.FAILED)) {
                finishTime = sdf.format(new Date(System.currentTimeMillis()));
            }

            // UPSTREAM decrease consumer count
            if (state.equals(TaskState.RUNNING) || state.equals(TaskState.FAILED) || state.equals(TaskState.CANCELLED)) {
                for (Parameter input : inParams.values()) {
                    input.decrementConsumerCount();
                }
            }

            // DOWNSTREAM set failed/cancelled
            if (state.equals(TaskState.FAILED)) {
                for (Parameter param : outParams.values()) {
                    if (param.getValue() == null) {
                        param.setFailed(true);
                    }
                }
            }
            if (state.equals(TaskState.CANCELLED)) {
                for (Parameter param : outParams.values()) {
                    if (param.getValue() == null) {
                        param.setCancelled(true);
                    }
                }
            }

        }
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    public String getStartTime() {
        return startTime;
    }

    public String getFinishTime() {
        return finishTime;
    }

    protected Task addInput(String name, String type) {
        inParams.put(name, new Parameter(type));
        return this;
    }

    protected Task addOutput(String name, String type) {
        outParams.put(name, new Parameter(type));
        return this;
    }

    protected Task addInput(String name) {
        inParams.put(name, new Parameter());
        return this;
    }

    protected Task addOutput(String name) {
        outParams.put(name, new Parameter());
        return this;
    }

    protected Parameter getInput(String name) {
        if (inParams.containsKey(name)) {
            return inParams.get(name);
        } else {
            throw new IllegalArgumentException();
        }
    }

    protected Object getInputValue(String name) {
        return getInput(name).getValue();
    }

    protected void setOutputValue(String name, Object value) {
        if (outParams.containsKey(name)) {
            outParams.get(name).setValue(value);
        } else {
            throw new IllegalArgumentException();
        }
    }

    private static final Logger log = Logger.getLogger(Task.class.getName());
}
